import Vue from 'vue';
import Vuex from 'vuex';


Vue.use(Vuex)
const store = new Vuex.Store({
    state:{
        taskList:localStorage.getItem("taskList")?(JSON).parse(localStorage.getItem("taskList")):[]
    },
    getters:{
        isAll(state,_this){
           return state.taskList.length>0 && state.taskList.length === _this.overNum;
        },
        overNum(state){
            return state.taskList.reduce((sum, item)=>{
                if(item.isChecked) sum+=1;
                return sum;
            },0)
        }
    },
    mutations:{
        DEL_TASK_BY_ID(state,id){
            if(window.confirm('确定要删除该信息吗')){
                state.taskList = state.taskList.filter(v=>v.id !== id);
            }
        },
        ALL_HANDLER(state){
            const isAll = !this.getters.isAll;
            state.taskList = state.taskList.map(item=>{
                item.isChecked = isAll;
                return item;
            })
        },
        UP_IS_CHECKED_BY_ID(state,id){
            state.taskList = state.taskList.map(item=>{
                if(item.id === id) item.isChecked = !item.isChecked;
                return item;
            })
        },
        ADD_TASK_LIST(state,event){
            const title = event.target.value.trim();
            if(!title){
                alert("请输入任务标题!")
                return;
            }
            state.taskList=[
                {
                    id:Math.random().toString(36).slice(2),
                    title,
                    isChecked:true,
                },
                ...state.taskList
            ];
            event.target.value = null;
        }
    }
});
export default store;